package org.dimock.proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;


public class DefaultDependencyResolver implements DependencyResolver {
	public Class<?>[] getAllMockableDependencies(Class<?> clazz){
		Set<Class<?>> interfacesToMock = new HashSet<Class<?>>();
		for (Method m : clazz.getMethods()){
			if (isMockable(m)){
				interfacesToMock.add( getInterfaceToMock(m) );
			}
		}
		return interfacesToMock.toArray( new Class<?>[]{} );
	}

	public void injectMockableDependencies(Object target, Object proxy){
		for (Method m : target.getClass().getMethods()){
			if (isMockable(m)){
				try {
					m.invoke(target, proxy);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	int paramCount(Method m) {
		return m.getParameterTypes().length;
	}


	
	Class<?> getInterfaceToMock(Method m) {
		return m.getParameterTypes()[0];
	}

	boolean isSetter(Method m) {
		return m.getName().startsWith("set");
	}
	
	boolean isInterface(Class<?> clazz) {
		return (clazz != null) && (clazz.isInterface());
	}
	
	boolean isMockable(Method m) {
		if (!isSetter(m) ) return false;
		if (paramCount(m) != 1) return false;
		return ( isInterface(m.getParameterTypes()[0]));
	}


}
